const koa = require('koa');
const http = require('http');
const router = require('./router/router');
const chat = require('./controller/chat');
const WebSocket = require('ws');
const mongoose = require('mongoose');
const bodyParser = require('koa-bodyparser');
const config = require('./config/config');
const app = new koa();
const server = http.createServer(app.callback());
const wss = new WebSocket.Server({ server });
const clients = []
server.on('request', (req, res) => {
  res.writeHead(200, {
    "Access-Control-Allow-Origin": "*",  // 白名单
    "Access-Control-Allow-Methods": "GET,POST,PUT,OPTIONS",
    // 不管向浏览器返回什么类型都可以
    "Access-Control-Allow-Headers": "Content-Type"
  })

})
wss.on('connection', (ws) => {
  console.log('New client connected', ws.CONNECTING);
  /* 
   // 处理收到的消息
   ws.on('message', (message) => {
     
     const data = JSON.parse(message);
     console.log(data);
     if (data.clientId) {
       ws.id=data.clientId
       clients.push(ws)
       return;
     }
     const {senderId, receiverId,msg}=data;
     chat.selectConversation(senderId, receiverId,msg)
     console.log(data);
     ws.send('client', 'hello client')
     clients.forEach(ws=>{
       if (ws.id==receiverId) {
         console.log(ws.id);
         ws.send(msg)
       }
     }) 
   });*/
  ws.on('message', (message) => {
    const result = JSON.parse(message);
    console.log(result);
    // 是否是登陆，登陆后绑定id
    if (result.login) {
      ws.socketIdxos = result.id;
    } else {
      // 这里只做一个小的场景，不是登陆就是发送信息
      // 根据存储的id 是否是要 发送的对象 来单独响应
      const {id,to,msg}=result;
      chat.selectConversation(id,to,msg)
     
      wss.clients.forEach(s => {
        if (s.socketIdxos == result.to && s.readyState == 1) {
          s.send(JSON.stringify({data:{
            msg: result.msg,
            id: result.id
          }} ));
        }
      });
    }
  })
  // 客户端断开连接
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods())
mongoose.connect(config.address, { useNewUrlParser: true }).then(() => {
  console.log('成功连接数据库');
}).catch(() => {
  console.log('连接数据库失败');
})

server.listen(4000, () => {
  console.log('服务端已启动在http://localhost:4000');
})

